<template>
  <view class="padding-bottom-button">
    <l-background :color="['#323840','#0A0B0D']" :bottom="isBuy ? '0' : bottom" />

    <buy-vip-success v-if="isBuy" :order-info="orderInfo" :choose-id="choose.id" />

    <template v-else>
      <view class="padding-30">
        <view class="text-center">
          <text class="text-32 color-border text-bold">按需升级，助力企业降本赠效！</text>
        </view>

        <view class="flex-row margin-top-30">
          <view v-for="(item,index) in versionList" :key="index" class="flex-item" :class="{'margin-left-20':index}">
            <vip-item :item="item" :active="chooseInx === index" @click="chooseVersion(item,index)" />
          </view>
        </view>

        <view class="table-title flex-row flex-center margin-top-30">
          <view class="flex-row flex-item">
            <view class="first text-center">
              <text class="text-28 color-border text-bold">权益对比详情</text>
            </view>
            <view v-for="(item,index) in versionList" :key="index" class="flex-item text-center">
              <text class="text-28 text-bold" style="color:#FED27F">{{ item.name }}</text>
            </view>
          </view>
        </view>

        <view class="table-body">
          <table-body title="操作平台" :labels="operationList" :vip-list="versionList" />

          <table-body title="功能模块" :labels="moduleList" :vip-list="versionList" format="showModule" />

          <table-body title="数量限制" :labels="numList" :vip-list="versionList" :show-right="false" format="showNumber" />

          <table-body title="服务支持" :labels="serveList" :vip-list="versionList" format="showServe" />
        </view>

        <view class="margin-top-16 custom-made flex-row align-center justify-between padding-lr-40 padding-tb-16">
          <view>
            <view class="margin-bottom-10">
              <text class="text-40 color-primary text-bold">功能私人定制</text>
            </view>
            <text class="text-24 color-primary">根据开发量计算，版本私有化部署</text>
          </view>
          <tui-button width="160rpx" height="64rpx" :size="28" @click="cell">立即咨询</tui-button>
        </view>
      </view>

      <buy-vip-info :show.sync="showBuyMessage" :info="orderInfo" @success="isBuy = true" />

      <safe-area-bottom id="safeBottom" />
      <l-bottom-button :text="buttonText" background="#0A0B0D" :shadow="false" :box-shadow="false" :disabled="disabled" @click="getVipOrder" />
    </template>
  </view>
</template>

<script>
import VipItem from '../components/vip-item/vip-item'
import TableBody from '../components/table-body/table-body'
import BuyVipInfo from '../components/buy-vip-info/buy-vip-info'
import BuyVipSuccess from '../components/buy-vip-success/buy-vip-success'
import { mapGetters } from 'vuex'
import { getVipServiceInfo } from '@/common/api/user'
import { loading, cellPhone } from '@/common/util'
import { getAllTree, getVIPPayOrderDetail } from '../api'
import { name } from '@/common/config'
let iapChannel = null
export default {
  name: 'BuyVip',
  components: {
    VipItem,
    TableBody,
    BuyVipInfo,
    BuyVipSuccess
  },
  data() {
    return {
      bottom: '0',
      orderInfo: {},
      disabled: false,
      showBuyMessage: false,
      isBuy: false,
      versionList: [], // 会员列表
      productIds: [], // 苹果产品id列表
      showApple: false, // 是否展示苹果支付
      vipPrice: '', // 会员价格
      vipName: '', // 会员名称
      chooseInx: 0, // 选择的会员下标
      choose: { // 选择的会员信息
        price: 0,
        id: '',
        canTry: 0,
        vipServiceTagList: [],
        sysRoleMenus: []
      },
      operationList: [
        { name: 'PC端' },
        { name: '小程序' },
        { name: 'App' }
      ], // 操作端
      moduleList: [], // 模块列表
      numList: [], // 数量限制列表
      serveList: [] // 服务支持列表
    }
  },
  computed: {
    buttonText() {
      return `${this.choose.price}元/年 ${this.vipInfo.vipServiceInfoId === this.choose.id ? '立即续费' : '立即购买'}`
    },
    ...mapGetters({
      vipInfo: 'vipInfo',
      showToast: 'showToast'
    })
  },
  created() {
    this.init()
  },
  mounted() {
    this.getBottom()
  },
  methods: {
    getBottom() {
      setTimeout(() => {
        this.getElementInfo('#safeBottom', res => {
          this.bottom = res.height + this.px() + 'px'
        })
      }, 300)
    },
    init() {
      this.getVipServiceInfo()
      this.getAllTree()
    },
    // 获取会员版本信息
    async getVipServiceInfo() {
      const [err, res] = await getVipServiceInfo()
      if (!this.$http.errorCheck(err, res)) return false
      this.versionList = res.data.data
      // 初始化数量限制展示文案
      this.formatShowNum()
      // 初始化选中项
      this.initChecked()

      /* #ifdef APP-PLUS*/
      this.versionList.forEach(item => {
        if (item.appleProductId) this.productIds.push(item.appleProductId)
      })
      this.getChannels()
      /* #endif*/
    },
    // 格式化数量限制/服务支持显示的文案
    formatShowNum() {
      this.versionList.forEach((item, index) => {
        this.formatNum(item.sysRoleMenus, index)
        this.serveList.push(...item.vipServiceTagList)
      })
      const numList = this.copyData(this.numList)
      const serveList = this.copyData(this.serveList)
      this.numList = []
      for (let i = 0; i < numList.length; i++) {
        this.numList.push(numList[i].substring(0, numList[i].indexOf('-')))
      }
      this.numList = Array.from(new Set(this.numList))

      this.serveList = []
      for (let i = 0; i < serveList.length; i++) {
        this.serveList.push(serveList[i].name)
      }
      this.serveList = Array.from(new Set(this.serveList))
    },
    // 格式化数量限制
    formatNum(data, index) {
      data.forEach((item) => {
        let subItem = []
        if (item.children.length) subItem = item.children
        if (item.limit || item.show) {
          if (this.versionList[index].newMenus) {
            this.versionList[index].newMenus.push(this.formatOperation(item))
            this.numList = this.numList.concat(this.formatOperation(item))
          } else {
            const newMenus = []
            newMenus.push(this.formatOperation(item))
            this.versionList[index].newMenus = newMenus
            this.numList = this.numList.concat(newMenus)
          }
        }
        if (this.versionList[index].menusList) {
          this.versionList[index].menusList += ',' + item.id
        } else {
          this.versionList[index].menusList = item.id
        }
        if (subItem.length) this.formatNum(subItem, index)
      })
    },
    // 格式化数量显示文案
    formatOperation(item) {
      let val = ''
      if (item.unit == 'month') {
        val += '每月' + item.label + '总数'
      } else if (item.unit == 'total') {
        val += item.label + '总数'
      } else if (item.unit == 'year') {
        val += '每年' + item.label + '总数'
      } else if (item.unit == 'day') {
        val += '每日' + item.label + '总数'
      } else {
        val += item.label + '总数'
      }
      let limit
      if (!item.limit || item.limit === -1) {
        limit = '无限制'
      } else {
        limit = item.limit
      }
      return val + '-' + limit
    },
    // 初始化需选中项
    initChecked() {
      if (this.vipInfo.vipServiceInfoId) {
        this.versionList.forEach((item, key) => {
          if (item.id === this.vipInfo.vipServiceInfoId) {
            this.chooseVersion(item, key)
          }
        })
      } else {
        this.chooseVersion(this.versionList[1], 1)
      }
    },
    // 验证是否可以苹果支付
    getChannels() {
      plus.payment.getChannels((channels) => {
        for (const i in channels) {
          const channel = channels[i]
          if (channel.id === 'appleiap') {
            iapChannel = channel
            this.requestOrder()
          }
        }
        if (!iapChannel) {
          this.showApple = false
          this.errorMsg()
        }
      }, () => {
        this.errorMsg()
      })
    },
    // 检测苹果支付环境
    requestOrder() {
      const l = loading('检测支付环境...')
      iapChannel.requestOrder(this.productIds, (orderList) => { // 必须调用此方法才能进行 iap 支付
        this.showApple = true
        l.hide()
      }, (e) => {
        l.hide()
        this.showApple = true
        this.errorMsg()
      })
    },
    // 苹果支付错误提示
    errorMsg() {
      const win = uni.getSystemInfoSync()
      const platform = win.platform
      if (platform === 'ios') {
        // this.toast('暂不支持苹果 iap 支付')
      }
    },
    // 选择版本
    chooseVersion(item, inx) {
      if (this.choose === inx) return
      this.chooseInx = inx
      this.choose = item
      this.vipPrice = item.price
      this.vipName = item.name
    },
    // 获取功能模块树
    async getAllTree() {
      const [err, res] = await getAllTree({ frontShow: 1 })
      if (!this.$http.errorCheck(err, res)) return false
      const menus = res.data.data[0].children
      menus.forEach(item => {
        this.moduleList.push(item)
        this.moduleList.push(...item.children)
      })
      const modules = [
        { right: false, name: 'GPS管理' },
        { right: false, name: '班车管理' },
        { right: false, name: '外调车辆' },
        { right: false, name: '档案管理' },
        { right: false, name: '供应链商城' },
        { right: true, name: '操作日志' },
        { right: true, name: `上线${name}旅游客运平台` }
      ]
      this.moduleList.push(...modules)
    },
    // 拨打电话
    cell() {
      cellPhone('0898-36692678')
    },
    // 预获取会员订单
    async getVipOrder() {
      this.disabled = true
      const l = loading('订单获取中...')
      const [err, res] = await getVIPPayOrderDetail({
        vipServiceInfoId: this.choose.id
      })
      this.disabled = false
      l.hide()
      if (!this.$http.errorCheck(err, res)) return false
      this.orderInfo = res.data.data
      this.showBuyMessage = true
    }
  }
}
</script>

<style scoped lang="scss">

.table-title{
  height: 88rpx;
  background: #393F47;
  border-radius: 20rpx 20rpx 0 0;
  @include position(sticky,0);
  z-index:10;
}
.first{
  flex: 2;
}
.table-body{
  border-left:2rpx solid #393F47;
}

.custom-made{
  background: rgba(218, 166, 101, 0.1);
  border: 2rpx solid $color-primary;
}

</style>
